<?php
defined('BASEPATH') OR exit('No direct script access allowed');

/**
 * 用户
 * @author www.dingwei.cn
 */
class User extends MY_Controller {
	
	/**
	 * 设置模型
	 * @var AdmSettingModel
	 */
	public $mSetting;
	
	/**
	 * 地址模型
	 * @var ConsumerAddressModel
	 */
	public $mAddress;
	
	/**
	 * 促销模型
	 * @var ConsumerPromotionModel
	 */
	public $mPromotion;

	/**
	 * 包邮卡
	 * @var ConsumerPostalCardModel
	 */
	public $mPostalCard;
	
	/**
	 * 银行模型
	 * @var ConsumerBankModel
	 */
	public $mBank;
	
	/**
	 * 意见反馈模型
	 * @var AdmFeedbackModel
	 */
	public $mFeedback;
	
	public function __construct(){
		parent::__construct();
	}

    /**
     * 个人中心
     */
	public function index(){
        $this->loadModel('ConsumerMessageModel', 'mMsg', 'consumer');
        $this->loadModel('ConsumerPromotionModel', 'mPromotion', 'consumer');
        $this->loadModel('AdmSettingModel', 'mSetting', 'admin');

        $info = $this->mUser->getInfo($this->userId);
        $info['portrait'] = $info['portrait']['xs'];
        $info['bonus'] = $this->mPromotion->getConsumerBonusNumber($this->userId); // 可用红包个数
        $info['coupon'] = $this->mPromotion->getConsumerCouponNumber($this->userId); // 可用代金券个数
        $sharp = $this->mSetting->get('sharp_title,sharp_icon,sharp_url,sharp_desc');
        $sharp['sharp_icon'] = getImage($sharp['sharp_icon'],'og');
        if(!$info['last_login_time']){
            $this->mUser->save(array('last_login_time'=>time()), $this->userId);
        }
        $data = array(
            'share' => json_encode($sharp, JSON_UNESCAPED_UNICODE),
            'info' => $info,
            'active' => 'user',
            'messageCount' => $this->mMsg->getMessageTotal($this->userId,0),
            'sign'=>wechat()->getSignPackage(),
            'title' => '我的'
        );

	    $this->view('user/index', $data, 'layer_mobile');
    }

    /**
     * 发送短信验证码
     */
    public function getVerifyCode(){

        //表单验证
        $vConf = array(
            array('mobile', '手机号码', 'required|valid_mobile'),
        );

        $this->formDataValidation($vConf);
        $code = mt_rand(10000,99999);
        $mobile = post('mobile');

        $tA = $this->mUser->getSmsCodeLogInfo($mobile);
        if($tA){
            $time = time() - $tA['addtime'];
            if($time < 60){
                $this->appReturn(0, '请等'.(60 - $time).'s后重新发送');
            }
        }

        $query = $this->mUser->addSmsCodeLog($mobile, $code);
        if( ! $query){
            $this->appReturn(0, '验证码发送失败');
        }
        $msg = $code.'（登录验证码，如非本人请忽略！）戈壁市集，为您提供即买即送的手机买菜服务！';
        $query = sendSms($mobile, $msg);
        if( ! $query){
            $this->appReturn(0, '验证码发送失败');
        }

        $this->appReturn(1, '验证码已发送');
    }


    /**
     * 注册发送短信验证码
     */
    public function getRegisterVerifyCode(){

        //表单验证
        $vConf = array(
            array('mobile', '手机号码', 'required|valid_mobile'),
        );

        $this->formDataValidation($vConf);
        $code = mt_rand(10000,99999);
        $mobile = post('mobile');
        $tB = $this->mUser->mobileIsExist($mobile);
        if($tB){
            $this->ajaxReturn(0, '手机号码已注册');
        }

        $tA = $this->mUser->getSmsCodeLogInfo($mobile);
        if($tA){
            $time = time() - $tA['addtime'];
            if($time < 60){
                $this->ajaxReturn(0, '请等'.(60 - $time).'s后重新发送');
            }
        }

        $query = $this->mUser->addSmsCodeLog($mobile, $code);
        if( ! $query){
            $this->ajaxReturn(0, '验证码发送失败');
        }
		$msg = '您正在进行新用户注册登录操作，验证码为'.$code.'，10分钟内有效（戈壁客服绝不会索取此验证码，切勿转发或告知他人）。';
        $query = sendSms($mobile, $msg);
        if( ! $query){
            $this->ajaxReturn(0, '验证码发送失败');
        }

        $this->ajaxReturn(1, '验证码已发送');
    }

	/**
	 * 忘记密码发送短信验证码
	 */
	public function getForgetPasswordVerifyCode(){
	
		//表单验证
		$vConf = array(
				array('mobile', '手机号码', 'required|valid_mobile'),
		);
	
		$this->formDataValidation($vConf);
		$code = mt_rand(10000,99999);
		$mobile = post('mobile');
		$tB = $this->mUser->mobileIsExist($mobile);
		if( ! $tB){
			$this->ajaxReturn(0, '手机号码未注册');
		}
	
		$tA = $this->mUser->getSmsCodeLogInfo($mobile);
		if($tA){
			$time = time() - $tA['addtime'];
			if($time < 60){
				$this->ajaxReturn(0, '请等'.(60 - $time).'s后重新发送');
			}
		}
	
		$query = $this->mUser->addSmsCodeLog($mobile, $code);
		if( ! $query){
			$this->ajaxReturn(0, '验证码发送失败');
		}
		$msg = '您正在进行登录密码找回操作，验证码为'.$code.'，10分钟内有效（戈壁客服绝不会索取此验证码，切勿转发或告知他人）。';
		$query = sendSms($mobile, $msg);
		if( ! $query){
			$this->ajaxReturn(0, '验证码发送失败');
		}
	
		$this->ajaxReturn(1, '验证码已发送');
	}

    /**
     *验证发送手机发送的验证码是否合法
     */
    public function verifyMobileCode(){
        //表单验证
        $vConf = array(
            array('mobile', '手机号码', 'required|valid_mobile'),
            array('code', '验证码', 'required'),
        );
        $this->formDataValidation($vConf);
        $mobile = trim(post('mobile'));
        $code = trim(post('code'));

        //验证验证码
        $tA = $this->mUser->getSmsCodeLogInfo($mobile, $code);
        if(empty($tA)) $this->ajaxReturn(0, '验证码错误');
        /*$smsExpire = time() - getCustomConfig('sms_expire') * 3600;
        if($tA['addtime'] < $smsExpire){
            $this->ajaxReturn(0, '验证码过期');
        }*/

        //验证手机
        $userId = $this->mUser->mobileIsExist($mobile);
        if( ! $userId){
            $this->ajaxReturn(0, '手机号码未注册');
        }
        $this->ajaxReturn(1, '验证成功');
    }

    /**
     * 检查验证码是否正确
     */
    public function checkVerifyCode(){
    	//表单验证
    	$vConf = array(
    			array('mobile', '手机号码', 'required|valid_mobile'),
    			array('code', '验证码', 'required'),
    	);
    	$this->formDataValidation($vConf);
    	
    	$mobile = trim(post('mobile'));
    	$code = trim(post('code'));
    	
    	//获取验证码
    	$tCode = $this->mUser->getSmsCodeLogInfo($mobile,$code);
    	if ( ! $tCode){
    		$this->ajaxReturn(0, '验证码错误');
    	}
    	
    	$smsExpire = time() - getCustomConfig('sms_expire') * 3600;
    	if($tCode['addtime'] < $smsExpire){
    		$this->ajaxReturn(0, '验证码过期');
    	}
		//只验证，不删除，等注册时，一起提交，删除验证码    	
    	$this->ajaxReturn(1,'验证成功',null, getUrl('user/setPassword?mobile='.$mobile.'&code='.$code));
    }
    
    /**
     * 用户注册
     */
    public function register(){

        if($_POST){

            //表单验证
            $vConf = array(
                array('mobile', '手机号码', 'required|valid_mobile'),
                array('code', '验证码', 'required'),
//                array('password', '密码', 'required|min_length[6]|max_length[15]'),
//                array('re_password', '确认密码', 'required|matches[password]'),
            );

            $mobile = trim(post('mobile'));
            $code = trim(post('code'));
            $pid = (int)post('pid');
            $pid = $pid > 0?$pid:0;
            if($pid == 0){
                $vConf[] = ['password', '密码', 'required|min_length[6]|max_length[15]'];
                $vConf[] = ['re_password', '确认密码', 'required|matches[password]'];
            }
            $this->formDataValidation($vConf);

            //验证手机
            $userId = $this->mUser->mobileIsExist($mobile);
            if($userId){
                $this->ajaxReturn(0, '手机号码已注册');
            }

            //验证验证码
            $tA = $this->mUser->getSmsCodeLogInfo($mobile, $code);
            if(empty($tA)) $this->ajaxReturn(0, '验证码错误');
            $smsExpire = time() - getCustomConfig('sms_expire') * 3600;
            if($tA['addtime'] < $smsExpire){
                $this->ajaxReturn(0, '验证码过期');
            }

            $jpush_code = uniqid().rand(1000, 9999).rand(100, 9999);
            $password = $pid >0 ?substr($mobile, -6):post('password');
            //注册账户信息
            $data = array(
                'mobile' => $mobile,
                'nickname' => substr($mobile,0,3).'****'.substr($mobile, -4),
                'password' => setPassword($password),
                'jpush_code' => $jpush_code,
                'message_push' => 2,
                'status' => 2,
                'parent_id' => $pid,
                'addtime' => time(),
                'last_login_time' => time(),
                'easemob_code'=> uniqid().rand(1000, 9999).rand(100, 9999)//环信账号
            );
            $data['easemob_pwd'] = setPassword($data['easemob_code']);//环信密码

            $this->db->trans_begin();
            if( $uId = $this->mUser->save($data)){

                //删除验证码
                if( !($this->mUser->deleteSmsCode($mobile))){
                    $this->db->trans_rollback();
                    $this->ajaxReturn(0, '注册失败');
                }

                //设置sessid
                $key = config_item('encryption_key');
                $sessionId = encryption($uId.$key.time().mt_rand(10,100000));
                if(empty($sessionId)){
                    $this->db->trans_rollback();
                    $this->ajaxReturn(0, '注册失败');
                }
                //注册送红包
                $this->loadModel('ConsumerPromotionModel', 'mPromotion', 'consumer');
                $this->db->select('id,name,type,money,surplus_number,send_start_time,send_end_time')
                    ->where(array('type' => 3,'status' => 2,'surplus_number >' => 0,'send_start_time <='=> time(),'send_end_time >=' => time()));
                $bonusList = $this->mPromotion->getAll($this->mPromotion->tbBonus);

                if($bonusList){
                    $bA = array();
                    $else = array();
                    foreach ($bonusList as $v){
                        $bA[] = array(
                            'bonus_id' => $v['id'],
                            'type' => $v['type'],
                            'consumer_id' => $uId,
                            'money' => $v['money'],
                            'status' => 1,
                            'addtime' => time()
                        );
                        $else[] = array(
                            'id' => $v['id'],
                            'surplus_number' => $v['surplus_number'] - 1,
                        );
                    }
                    if(!($this->mPromotion->saveBonusLog($bA, 0, true))){
                        $this->db->trans_rollback();
                        $this->appReturn(0, '红包赠送失败');
                    }
                    //更新剩余红包数量
                    if(!($this->mPromotion->save($else, 0, true))){
                        $this->db->trans_rollback();
                        $this->appReturn(0, '红包赠送失败');
                    }
                }

                // 注册赠送积分数量
                $this->loadModel('AdmSettingModel', 'mSetting', 'admin');
                $this->loadModel('ConsumerMallModel', 'mMall');
                $number = $this->mSetting->get('regiser_integral_number'); // 注册赠送积分数量
                if ($number > 0){
                    $integral = $this->mUser->save(array('integral'=> $number), $uId);
                    if (!$integral){
                        $this->db->trans_rollback();
                        $this->ajaxReturn(0, '注册失败');
                    }
                    // 添加积分记录
                    $integralLogData = array(
                        'consumer_id' => $uId,
                        'type' => 2,
                        'integral' => $number,
                        'status' => 2,
                        'addtime' => time(),
                    );
                    $integralLog = $this->mMall->saveLog($integralLogData);
                    if (!$integralLog){
                        $this->db->trans_rollback();
                        $this->ajaxReturn(0, '注册失败');
                    }
                }

                // 注册经验奖励数量
                $this->loadModel('ConsumerExperienceValueModel', 'mExperience');
                $experience = $this->mSetting->get('register_experience_value_number'); // 注册经验奖励数量
                if ($experience > 0){
                    $exp = $this->mUser->save(array('experience_value'=> $experience), $uId);
                    if (!$exp){
                        $this->db->trans_rollback();
                        $this->ajaxReturn(0, '注册失败');
                    }
                    // 添加经验奖励记录
                    $logData = array(
                        'consumer_id' => $uId,
                        'type' => 1,
                        'experience_value' => $number,
                        'addtime' => time(),
                    );
                    $log = $this->mExperience->save($logData);
                    if (!$log){
                        $this->db->trans_rollback();
                        $this->ajaxReturn(0, '注册失败');
                    }
                }
                //赠送包邮卡
                $this->loadModel('ConsumerPostalCardModel', 'mPostalCard', 'consumer');
                $info = $this->mPostalCard->getCard(['type'=>1,'status'=>2]);
                if(!empty($info)){
                    for($i = 0 ; $i < $info['send_number'] ; $i++ ){
                        $lData[] = array(
                            'postal_card_id' => $info['id'],
                            'type' => $info['type'],
                            'consumer_id' => $uId,
                            'order_id' => 0,
                            'money' => $info['money'],
                            'status' => 1,
                            'addtime' => time(),
                            'begintime'=> time(),
                            'userendtime'=>strtotime("+".$info['use_date'].' days')
                        );
                    }
                    if(isset($lData)){
                        $tA = $this->mPostalCard->insertBatch($this->mPostalCard->tbPostalCardLog, $lData);
                        if (!$tA){
                            $this->db->trans_rollback();
                            $this->ajaxReturn(0, '注册失败');
                        }
                        //推送消息
                        $this->loadModel('ConsumerMessageModel', 'mMessage', 'consumer');
                        $title = '赠送'.$info['send_number'].'张包邮体验券，享免费配送到家.';
                        $content = '亲，'.$info['send_number'].'张包邮体验券已存入您的账户，让您尊享生鲜果蔬1小时免费配送到家，请您查收。';
                        $msgdata[] = array(
                            'consumer_id' => $uId,
                            'type' => 2,
                            'title' => $title,
                            'content' => $content,
                            'content_detail' => $content,
                            'addtime' => time(),
                        );
                        $tA = $this->mMessage->batchSave($msgdata);
                        if (!$tA){
                            $this->db->trans_rollback();
                            $this->ajaxReturn(0, '推送失败');
                        }
                        jpush($title, $content, 1, $data['jpush_code']);
                    }
                }

                if($this->mUser->addSession($uId, $sessionId, 2)){
                    setcookie('wx_sessionid', encode($sessionId), 0, '/');

                    $reUrl = getUrl('user/index');
                    if($pid){
                        $reUrl = getUrl('app/home/share');
                        //清空cookie
                        setcookie('wx_sessionid', '');
                    }


                    $this->db->trans_commit();
                    $this->ajaxReturn(1, '注册成功',  null, $reUrl);
                }
            }
        }

        $this->view('user/register', ['title' => '用户注册'], 'wx_validation,toastmessage,layer_mobile');
    }

    public function setPassword(){
        $data = array(
            'title' => '设置登录密码',
            'mobile' => trim(get('mobile')),
            'code' => trim(get('code')),
        );
        $this->view('user/setPassword', $data, 'wx_validation,toastmessage,layer_mobile');
    }
    /**
     * 验证码登录
     */
    public function loginByCode(){
        //表单验证
        $vConf = array(
            array('mobile', '手机号码', 'required|valid_mobile'),
            array('code', '验证码', 'required'),
        );
        $this->formDataValidation($vConf);
        $mobile = post('mobile');
        $code = post("code");
        $merchantId = intval(post('merchant_id'));
        $pid = 0;
        //验证验证码
        $sc = $this->mUser->getSmsCodeLogInfo($mobile, $code);
        if(empty($sc)) $this->appReturn(0, '验证码错误');
        $smsExpire = time() - getCustomConfig('sms_expire') * 3600;
        if($sc['addtime'] < $smsExpire){
            $this->appReturn(0, '验证码过期');
        }
        $url = getUrl('user/index');
        if($merchantId){
            $url = getUrl('product/merchant?merchant_id='.$merchantId);
        }

        //验证手机
        $userId = $this->mUser->mobileIsExist($mobile);
        if($userId){
            //登录
            //设置sessid
            $tA = $this->mUser->getInfo($userId);
            //设置sessid
            $key = config_item('encryption_key');
            $sessionId = encryption($tA['id'].$key.time().mt_rand(10,100000));
            if(empty($sessionId)){
                $this->ajaxReturn(0, '登录失败');
            }

            if($this->mUser->addSession($tA['id'], $sessionId, 2)){
                $this->sessionId = $sessionId;
                $data = array(
                    'sessionid' => encode($sessionId),
                    'jpush_code' => $tA['jpush_code'],
                    'name' => $tA['nickname'],
                    'is_pay_passwd'=>empty($tA['pay_passwd'])?"1":"2",
                );
                // 查询是否有openid，有则绑定openid
                $openid = !empty($_COOKIE['wx_openid']) ? decode($_COOKIE['wx_openid']) : 0;

                if ( ! $this->mUser->save(array('last_login_time'=>time(), 'openid' => $openid),$tA['id'])){
                    $this->ajaxReturn(0, '登录失败', $data);
                }
                setcookie('wx_sessionid', encode($sessionId), 0, '/');

                $this->ajaxReturn(1, '已登录', null, $url);
            }

            $this->ajaxReturn(0, '登录失败');
        }else{
            //注册
            $jpush_code = uniqid().rand(1000, 9999).rand(100, 9999);
            $password = $pid >0 ?substr($mobile, -6):post('password');
            //注册账户信息
            $data = array(
                'mobile' => $mobile,
                'nickname' => substr($mobile,0,3).'****'.substr($mobile, -4),
                'password' => setPassword($password),
                'jpush_code' => $jpush_code,
                'message_push' => 2,
                'status' => 2,
                'parent_id' => $pid,
                'last_login_time' => time(),
                'addtime' => time(),
            );

            $this->db->trans_begin();
            if( $uId = $this->mUser->save($data)) {

                //删除验证码
                if (!($this->mUser->deleteSmsCode($mobile))) {
                    $this->db->trans_rollback();
                    $this->ajaxReturn(0, '注册失败');
                }

                //设置sessid
                $key = config_item('encryption_key');
                $sessionId = encryption($uId . $key . time() . mt_rand(10, 100000));
                if (empty($sessionId)) {
                    $this->db->trans_rollback();
                    $this->ajaxReturn(0, '注册失败');
                }
                //注册送红包
                $this->loadModel('ConsumerPromotionModel', 'mPromotion', 'consumer');
                $this->db->select('id,name,type,money,surplus_number,send_start_time,send_end_time')
                    ->where(array('type' => 3, 'status' => 2, 'surplus_number >' => 0, 'send_start_time <=' => time(), 'send_end_time >=' => time()));
                $bonusList = $this->mPromotion->getAll($this->mPromotion->tbBonus);

                if ($bonusList) {
                    $bA = array();
                    $else = array();
                    foreach ($bonusList as $v) {
                        $bA[] = array(
                            'bonus_id' => $v['id'],
                            'type' => $v['type'],
                            'consumer_id' => $uId,
                            'money' => $v['money'],
                            'status' => 1,
                            'addtime' => time()
                        );
                        $else[] = array(
                            'id' => $v['id'],
                            'surplus_number' => $v['surplus_number'] - 1,
                        );
                    }
                    if (!($this->mPromotion->saveBonusLog($bA, 0, true))) {
                        $this->db->trans_rollback();
                        $this->appReturn(0, '红包赠送失败');
                    }
                    //更新剩余红包数量
                    if (!($this->mPromotion->save($else, 0, true))) {
                        $this->db->trans_rollback();
                        $this->appReturn(0, '红包赠送失败');
                    }
                }

                // 注册赠送积分数量
                $this->loadModel('AdmSettingModel', 'mSetting', 'admin');
                $this->loadModel('ConsumerMallModel', 'mMall');
                $number = $this->mSetting->get('regiser_integral_number'); // 注册赠送积分数量
                if ($number > 0) {
                    $integral = $this->mUser->save(array('integral' => $number), $uId);
                    if (!$integral) {
                        $this->db->trans_rollback();
                        $this->ajaxReturn(0, '注册失败');
                    }
                    // 添加积分记录
                    $integralLogData = array(
                        'consumer_id' => $uId,
                        'type' => 2,
                        'integral' => $number,
                        'status' => 2,
                        'addtime' => time(),
                    );
                    $integralLog = $this->mMall->saveLog($integralLogData);
                    if (!$integralLog) {
                        $this->db->trans_rollback();
                        $this->ajaxReturn(0, '注册失败');
                    }
                }

                // 注册经验奖励数量
                $this->loadModel('ConsumerExperienceValueModel', 'mExperience');
                $experience = $this->mSetting->get('register_experience_value_number'); // 注册经验奖励数量
                if ($experience > 0) {
                    $exp = $this->mUser->save(array('experience_value' => $experience), $uId);
                    if (!$exp) {
                        $this->db->trans_rollback();
                        $this->ajaxReturn(0, '注册失败');
                    }
                    // 添加经验奖励记录
                    $logData = array(
                        'consumer_id' => $uId,
                        'type' => 1,
                        'experience_value' => $number,
                        'addtime' => time(),
                    );
                    $log = $this->mExperience->save($logData);
                    if (!$log) {
                        $this->db->trans_rollback();
                        $this->ajaxReturn(0, '注册失败');
                    }
                }
                //赠送包邮卡
                $this->loadModel('ConsumerPostalCardModel', 'mPostalCard', 'consumer');
                $info = $this->mPostalCard->getCard(['type' => 1, 'status' => 2]);
                if (!empty($info)) {
                    for ($i = 0; $i < $info['send_number']; $i++) {
                        $lData[] = array(
                            'postal_card_id' => $info['id'],
                            'type' => $info['type'],
                            'consumer_id' => $uId,
                            'order_id' => 0,
                            'money' => $info['money'],
                            'status' => 1,
                            'addtime' => time(),
                            'begintime' => time(),
                            'userendtime' => strtotime("+" . $info['use_date'] . ' days')
                        );
                    }
                    if (isset($lData)) {
                        $tA = $this->mPostalCard->insertBatch($this->mPostalCard->tbPostalCardLog, $lData);
                        if (!$tA) {
                            $this->db->trans_rollback();
                            $this->ajaxReturn(0, '注册失败');
                        }
                        //推送消息
                        $this->loadModel('ConsumerMessageModel', 'mMessage', 'consumer');
                        $title = '赠送' . $info['send_number'] . '张包邮体验券，享免费配送到家.';
                        $content = '亲，' . $info['send_number'] . '张包邮体验券已存入您的账户，让您尊享生鲜果蔬1小时免费配送到家，请您查收。';
                        $msgdata[] = array(
                            'consumer_id' => $uId,
                            'type' => 2,
                            'title' => $title,
                            'content' => $content,
                            'content_detail' => $content,
                            'addtime' => time(),
                        );
                        $tA = $this->mMessage->batchSave($msgdata);
                        if (!$tA) {
                            $this->db->trans_rollback();
                            $this->ajaxReturn(0, '推送失败');
                        }
                        jpush($title, $content, 1, $data['jpush_code']);
                    }
                }

                if ($this->mUser->addSession($uId, $sessionId, 2)) {
                    setcookie('wx_sessionid', encode($sessionId), 0, '/');

                    $this->db->trans_commit();
                    $this->ajaxReturn(1, '注册成功', null, $url);
                }
            }
        }

    }

	/**
	 * 用户登录
	 */
	public function login(){
		if($_POST){
            //表单验证
            $vConf = array(
                array('mobile', '手机号码', 'required|valid_mobile'),
                array('password', '密码', 'required|min_length[6]|max_length[15]'),
            );

            $this->formDataValidation($vConf);
            $mobile = trim(post('mobile'));
            $password = setPassword(post('password'));
            $merchantId = intval(post('merchant_id'));

            $tA = $this->mUser->getInfoByMobileAndPassword($mobile, $password);
            if(empty($tA)){
                $this->ajaxReturn(0, '用户不存在或密码错误');
            }
            if($tA['status'] < 2){
                $this->ajaxReturn(0, '账户已禁用');
            }

            //设置sessid
            $key = config_item('encryption_key');
            $sessionId = encryption($tA['id'].$key.time().mt_rand(10,100000));
            if(empty($sessionId)){
                $this->ajaxReturn(0, '登录失败');
            }

            if($this->mUser->addSession($tA['id'], $sessionId, 2)){
                $this->sessionId = $sessionId;
                $data = array(
                    'sessionid' => encode($sessionId),
                    'jpush_code' => $tA['jpush_code'],
                    'easemob_code' => $tA['easemob_code'],
                    'easemob_pwd'=>$tA['easemob_pwd'],
                    'name' => $tA['nickname'],
                    'is_pay_passwd'=>empty($tA['pay_passwd'])?"1":"2",
                );
                // 查询是否有openid，有则绑定openid
                $openid = !empty($_COOKIE['wx_openid']) ? decode($_COOKIE['wx_openid']) : 0;
                
                if ( ! $this->mUser->save(array('last_login_time'=>time(), 'openid' => $openid),$tA['id'])){
                    $this->ajaxReturn(0, '登录失败', $data);
                }
                setcookie('wx_sessionid', encode($sessionId), 0, '/');
                $url = getUrl('user/index');
                if($merchantId){
                    $url = getUrl('product/merchant?merchant_id='.$merchantId);
                }
                $this->ajaxReturn(1, '已登录', null, $url);
            }
            $this->ajaxReturn(0, '登录失败');
        }
        if(!isset($_COOKIE['wx_openid']) || !$_COOKIE['wx_openid']){
            $openid = wechat()->get_openid();
            setcookie('wx_openid', encode($openid), 0, '/');
        }
        $this->view('user/login',['title' => '用户登录','merchant_id' => get('merchant_id')], 'wx_validation,toastmessage,layer_mobile');
	}
	
	/**
	 * 忘记密码
	 */
	public function forgetPassword(){
		if($_POST){
            //表单验证
            $vConf = array(
                array('mobile', '手机号码', 'required|valid_mobile'),
                array('code', '验证码', 'required'),
                array('password', '密码', 'required|min_length[6]|max_length[15]'),
            );
            $this->formDataValidation($vConf);
            $mobile = trim(post('mobile'));
            $code = trim(post('code'));

            //验证验证码
            $tA = $this->mUser->getSmsCodeLogInfo($mobile, $code);
            if(empty($tA)) $this->ajaxReturn(0, '验证码错误');
            $smsExpire = time() - getCustomConfig('sms_expire') * 3600;
            if($tA['addtime'] < $smsExpire){
                $this->ajaxReturn(0, '验证码过期');
            }

            //验证手机
            $userId = $this->mUser->mobileIsExist($mobile);
            if( ! $userId){
                $this->ajaxReturn(0, '手机号码未注册');
            }

            $data = array(
                'password' => setPassword(post('password'))
            );

            if($this->mUser->save($data, $userId)){
                $this->mUser->deleteSmsCode($mobile);//删除验证码
                $this->ajaxReturn(1, '密码已更改', getUrl('user/login'));
            }

            $this->ajaxReturn(0, '修改失败');
        }

        $this->view('user/forgetPassword', ['title' => '重置密码'], 'wx_validation,toastmessage,layer_mobile');
	}

    /**
     * 修改密码
     */
    public function password(){

        //表单验证
        $vConf = array(
            array('old_password', '旧密码', 'required|min_length[6]|max_length[15]'),
            array('password', '新密码', 'required|min_length[6]|max_length[15]'),
            array('re_password', '确认密码', 'required|matches[password]'),
        );
        $this->formDataValidation($vConf);
        $mobile = $this->userMobile;

        $oldPassword = setPassword(post('old_password'));
        //验证手机
        $userId = $this->mUser->getInfoByMobileAndPassword($mobile, $oldPassword);
        if(empty($userId)){
            $this->ajaxReturn(0, '原密码错误');
        }

        $data = array(
            'password' => setPassword(post('password'))
        );

        if($this->mUser->save($data, $this->userId)){
            $this->ajaxReturn(1, '密码修改成功，请重新登录');
        }
        $this->ajaxReturn(0, '修改失败');
    }
    
    /**
     * 获取各新消息状态
     */
    public function getMsgStatus(){
    	
    	$this->loadModel('ConsumerMessageModel', 'mMsg','consumer');
    	$this->loadModel('ConsumerPromotionModel', 'mPromotion','consumer');
    	$this->loadModel('ConsumerCartModel', 'mCart','consumer');
    	$tA = array(
    			'balance'=>1,//新消息
    			'integral'=>1,//新消息
    			'bonus'=>$this->mPromotion->appGetBonusLogList($this->userId, 1,0,true) > 0 ? "2":"1",
    			'coupon'=>$this->mPromotion->appGetCouponLogList($this->userId, 1,0,true) > 0 ? "2":"1",
    			'message_num' =>$this->mMsg->getMessageTotal($this->userId,1),
    			'order_num' => $this->mMsg->getMessageTotal($this->userId,2),
    			'shop_car_num'=>$this->mCart->getProductCount($this->userId),//购物车数量
    	);
    	
    	$this->ajaxReturn(1,'',$tA);
    }
    
    /**
     * 上传头像
     */
    public function portrait(){
    	
    	$path = 'uploads/member/'.$this->port.'/'.$this->userId.'/portrait';
    	if(empty($_FILES['portrait'])){
    		$this->ajaxReturn(0, '请选择上传头像');
    	}
    	
    	$tA = imageUpload($path, 'portrait', 'portrait', true, 250, 250);
    	if( ! $tA['status']){
    		$this->ajaxReturn(0, '头像上传失败');
    	}
    	$rs = $this->mUser->save(array('portrait' => $tA['data']), $this->userId);
    	if($rs){
    		$this->ajaxReturn(1, '头像上传成功', getImage($tA['data'], 'xs'));
    	}
    	$this->ajaxReturn(0, '头像上传失败');
    }
    
    /**
     * 设置支付密码
     */
    public function setPayPasswd(){
    	if($_POST){
            //表单验证
            $vConf = array(
                array('code', '短信验证码', 'required'),
                array('password', '支付密码', 'required|min_length[6]'),
                array('repassword', '确认密码', 'required|matches[password]|min_length[6]'),
            );
            $this->formDataValidation($vConf);
            //获取
            $code = post('code');
            $password = post('password');
            $repassword = post('repassword');

            /**
             * 验证手机
             */
            if ( ! $this->mUser->mobileIsExist($this->userMobile)){
                $this->ajaxReturn(0,'手机号错误');
            }

            /**
             * 验证验证码
             */
            $tCode = $this->mUser->getSmsCodeLogInfo($this->userMobile, $code);
            if(! $tCode){
                $this->ajaxReturn(0, '验证码错误');
            }
            $smsExpire = time() - getCustomConfig('sms_expire') * 3600;
            if($tCode['addtime'] < $smsExpire){
                $this->ajaxReturn(0, '验证码过期');
            }

            /**
             * 设置密码
             */
            $this->db->trans_begin();//事务

            if ( ! $this->mUser->save(array('pay_passwd'=>setPassword($password)),$this->userId)){
                $this->db->trans_rollback();
                $this->ajaxReturn(0,'设置密码失败');
            }

            //删除验证码
            if ( ! $this->mUser->deleteSmsCode($this->userMobile)){
                $this->db->trans_rollback();
                $this->ajaxReturn(0,'设置失败');
            }

            $this->db->trans_commit();
            $this->ajaxReturn(1,'设置成功',null, getUrl('user/index'));
        }

        $this->view('user/setPayPasswd', ['title' => '重置支付密码'], 'wx_validation,toastmessage,layer_mobile');
    }
    
    /**
     * 修改支付密码
     */
    public function savePayPasswd(){
    	if($_POST){
            //表单验证
            $vConf = array(
                array('oldpassword', '旧支付密码', 'required|min_length[6]'),
                array('password', '支付密码', 'required|min_length[6]'),
                array('repassword', '确认密码', 'required|matches[password]|min_length[6]'),
            );
            $this->formDataValidation($vConf);
            //获取
            $oldpassword = post('oldpassword');
            $password = post('password');
            $repassword = post('repassword');

            /**
             * 验证密码
             */
            if ( ! $tInfo = $this->mUser->getInfo($this->userId)){
                $this->ajaxReturn(0,'登录失效');
            }

            if ($tInfo['pay_passwd'] !== setPassword($oldpassword)){
                $this->ajaxReturn(0,'旧支付密码错误');
            }

            /**
             * 修改密码
             */
            if ( ! $this->mUser->save(array('pay_passwd'=>setPassword($password)),$this->userId)){
                $this->ajaxReturn(0,'修改失败');
            }

            $this->ajaxReturn(1,'修改成功',null,getUrl('user/index'));
        }

        $this->view('user/savePayPasswd', ['title' => '修改支付密码'], 'wx_validation,toastmessage,layer_mobile');
    }
    
    /**
     * 修改登录密码
     */
    public function savePasswd(){
    	if($_POST){
            //表单验证
            $vConf = array(
                array('oldpassword', '旧支密码', 'required|min_length[6]'),
                array('password', '新密码', 'required|min_length[6]'),
                array('repassword', '确认密码', 'required|matches[password]|min_length[6]'),
            );
            $this->formDataValidation($vConf);
            //获取
            $oldpassword = post('oldpassword');
            $password = post('password');
            $repassword = post('repassword');

            /**
             * 验证密码
             */
            if ( ! $tInfo = $this->mUser->getInfo($this->userId)){
                $this->ajaxReturn(0,'登录失效');
            }

            if ($tInfo['password'] !== setPassword($oldpassword)){
                $this->ajaxReturn(0,'旧密码错误');
            }

            /**
             * 修改密码
             */
            if ( ! $this->mUser->save(array('password'=>setPassword($password)),$this->userId)){
                $this->ajaxReturn(0,'修改失败');
            }

            $this->ajaxReturn(1,'修改成功',null, getUrl('user/index'));
        }

        $this->view('user/savePasswd', ['title' => '修改登录密码'], 'wx_validation,toastmessage,layer_mobile');
    }
    
    /**
     * 获取支付密码发送短信验证码
     */
    public function getPayPasswdVerifyCode(){
    	
    	$code = mt_rand(10000,99999);
    	$tB = $this->mUser->mobileIsExist($this->userMobile);
    	if( ! $tB){
    		$this->ajaxReturn(0, '手机号码未注册');
    	}
    	
    	$tA = $this->mUser->getSmsCodeLogInfo($this->userMobile);
    	if($tA){
    		$time = time() - $tA['addtime'];
    		if($time < 60){
    			$this->ajaxReturn(0, '请等'.(60 - $time).'s后重新发送');
    		}
    	}
    	
    	$query = $this->mUser->addSmsCodeLog($this->userMobile, $code);
    	if( ! $query){
    		$this->ajaxReturn(0, '验证码发送失败');
    	}
		 $msg = '您正在进行支付密码设置操作，验证码为'.$code.'，10分钟内有效（戈壁客服绝不会索取此验证码，切勿转发或告知他人）。';
    	//获取用户信息
        $userInfo = $this->mUser->getInfo($this->userId);
    	if($userInfo['has_pay_passwd'] == 2){
    	    $msg = '您正在进行支付密码找回操作，验证码为'.$code.'，10分钟内有效（戈壁客服绝不会索取此验证码，切勿转发或告知他人）。';
        }
    	$query = sendSms($this->userMobile, $msg);
    	if( ! $query){
    		$this->ajaxReturn(0, '验证码发送失败');
    	}
    	
    	$this->ajaxReturn(1, '验证码已发送');
    }

    ////////////////////////////////////////////////////////////
    //-----------------------------------------------
    //|	第三方登录
    //-----------------------------------------------

    /**
     * 第三方登录短信验证码
     */
    public function getThirdVerifyCode(){

        //表单验证
        $vConf = array(
            array('mobile', '手机号码', 'required|valid_mobile'),
        );

        $this->formDataValidation($vConf);
        $code = mt_rand(10000,99999);
        $mobile = post('mobile');
        $tA = $this->mUser->getSmsCodeLogInfo($mobile);
        if($tA){
            $time = time() - $tA['addtime'];
            if($time < 60){
                $this->ajaxReturn(0, '请等'.(60 - $time).'s后重新发送');
            }
        }

        $query = $this->mUser->addSmsCodeLog($mobile, $code);
        if( ! $query){
            $this->ajaxReturn(0, '验证码发送失败');
        }
        $query = sendSms($mobile, '您正在进行第三方绑定操作，验证码为'.$code);
        if( ! $query){
            $this->ajaxReturn(0, '验证码发送失败');
        }

        $this->ajaxReturn(1, '验证码已发送');
    }

    /**
     * 第三方登录
     */
    public function thirdParty(){
        //表单验证
        $vConf = array(
            array('type', '第三方对应值', 'required|in_list[1,2]'), // 1 微信（wxUnionId）   2 QQ（qqUnionId）
            array('value', 'unionId的值', 'required'),
        );
        $this->formDataValidation($vConf);
        $type = post('type');// wxUnionId,qqUnionId
        $value = post('value');
        $keyword = $type == 1 ? 'wxUnionId' : 'qqUnionId';
        $tA = $this->mUser->getInfoByMobileAndPassword(0, 0, array($keyword => $value));
        if(!empty($tA)){
            if($tA['status'] < 2){
                $this->ajaxReturn(0, '账户已禁用');
            }
            //设置sessid
            $key = config_item('encryption_key');
            $sessionId = encryption($tA['id'].$key.time().mt_rand(10,100000));
            if(empty($sessionId)){
                $this->ajaxReturn(0, '登录失败');
            }
            if($this->mUser->addSession($tA['id'], $sessionId, 2)){
                $this->sessionId = $sessionId;
                $data = array(
                    'sessionid' => encode($sessionId),
                    'jpush_code' => $tA['jpush_code'],
                    'easemob_code' => $tA['easemob_code'],
                    'easemob_pwd'=>$tA['easemob_pwd'],
                    'name' => $tA['nickname'],
                    'is_pay_passwd'=>empty($tA['pay_passwd'])?"1":"2",
                );

                if ( ! $this->mUser->save(array('last_login_time'=>time()),$tA['id'])){
                    $this->ajaxReturn(0, '登录失败', $data);
                }

                $this->ajaxReturn(1, '已登录', $data);
            }
        }else{
            $this->ajaxReturn(-1,'请绑定账号');
        }
    }

    /**
     * 第三方绑定
     *
     */
    public function thirdBinding(){
        //表单验证
        $vConf = array(
            array('mobile', '手机号码', 'required|valid_mobile'),
            array('code', '验证码', 'required'),
            array('type', '第三方对应值', 'required|in_list[1,2]'),// 1 微信（wxUnionId）   2 QQ（qqUnionId）
            array('value', 'unionId的值', 'required'),
//            array('head_portrait', '头像', 'required'),
            array('nickname', '昵称', 'required'),
        );
        $this->formDataValidation($vConf);
        $mobile = post('mobile');
        $code = post("code");
        $type = post("type");
        $keyword = $type == 1 ? 'wxUnionId' : 'qqUnionId';
        $value = post('value');
//        $head_portrait = post('head_portrait'); // 头像
        $nickname = post('nickname'); // 昵称

        //验证验证码
        $sc = $this->mUser->getSmsCodeLogInfo($mobile, $code);
        if(empty($sc)) $this->ajaxReturn(0, '验证码错误');
        $smsExpire = time() - getCustomConfig('sms_expire') * 3600;
        if($sc['addtime'] < $smsExpire){
            $this->ajaxReturn(0, '验证码过期');
        }

        //验证手机
        $userId = $this->mUser->mobileIsExist($mobile);

        if($userId){
            // 手机号码已注册, 绑定第三方信息
            $tA = $this->mUser->getInfoByMobileAndPassword(0, 0, array('id' => $userId));
            if($tA['status'] < 2){
                $this->ajaxReturn(0, '账户已禁用');
            }
            $data = array($keyword => $value);
            $rS = $this->mUser->save($data, $userId);
            if (!$rS){
                $this->ajaxReturn(0, '绑定失败');
            }
        }else{
            // 未注册， 添加新用户绑定第三方登陆
            $data = array(
                'mobile' => $mobile,
                'nickname' => $nickname,
                'jpush_code' => uniqid().rand(1000, 9999).rand(100, 9999),
                $keyword => $value
            );
            $userId = $this->mUser->save($data);
            if (!$userId){
                $this->ajaxReturn(0, '绑定失败');
            }
            $tA = $this->mUser->getInfoByMobileAndPassword(0, 0, array('id' => $userId));
        }

        //设置sessid
        $key = config_item('encryption_key');
        $sessionId = encryption($tA['id'].$key.time().mt_rand(10,100000));
        if(empty($sessionId)){
            $this->ajaxReturn(0, '登录失败');
        }
        if($this->mUser->addSession($tA['id'], $sessionId, 2)){
            $this->sessionId = $sessionId;
            $data = array(
                'sessionid' => encode($sessionId),
                'jpush_code' => $tA['jpush_code'],
                'easemob_code' => $tA['easemob_code'],
                'easemob_pwd'=>$tA['easemob_pwd'],
                'name' => $tA['nickname'],
                'is_pay_passwd'=>empty($tA['pay_passwd'])?"1":"2",
            );

            if ( ! $this->mUser->save(array('last_login_time'=>time()),$tA['id'])){
                $this->ajaxReturn(0, '登录失败', $data);
            }

            $this->ajaxReturn(1, '已登录', $data);
        }
    }

    /**
     *  第三方解绑
     */
    public function offBinding(){
        //表单验证
        $vConf = array(
            array('type', '第三方对应值', 'required|in_list[1,2]'), // 1 微信（wxUnionId）   2 QQ（qqUnionId）
        );
        $this->formDataValidation($vConf);
        $type = post('type');// wxUnionId,qqUnionId
        $keyword = $type == 1 ? 'wxUnionId' : 'qqUnionId';
        $tA = $this->mUser->save(array($keyword => ''), $this->userId);
        if(!$tA){
            $this->ajaxReturn(0,'解绑失败');
        }
        $this->ajaxReturn(1,'解绑成功');
    }

    ////////////////////////////////////////////////////////////
    //-----------------------------------------------
    //|	收货地址
    //-----------------------------------------------
    public function address(){
    	$this->loadModel('ConsumerAddressModel', 'mAddress', 'consumer');

        $lat = trim(post('latitude'));
        $lng = trim(post('longitude'));
        if(!$lat){
            $lat = trim(get('latitude'));
        }
        if(!$lng){
            $lng = trim(get('longitude'));
        }
        $list = $this->mAddress->appGetList($this->userId, 1, true, $lat, $lng);
        $data = array(
            'list' => $list,
            'title' => '收货地址',
            'lat' =>$lat,
            'lng' =>$lng
        );
    	$this->view('user/address', $data, 'layer_mobile,jquery_we_ui');
    }

    /**
     * 获取地址列表
     */
    public function getAddressList(){
        //表单验证
        $vConf = array(
            array('page', '页码', 'required|is_natural_no_zero'),
        );
        $this->formDataValidation($vConf);
        $this->loadModel('ConsumerAddressModel', 'mAddress', 'consumer');
        $page = (int)post('page');
        $page += 1;
        $list = $this->mAddress->appGetList($this->userId, $page);
        $this->ajaxReturn(1, '', $list);
    }

    /**
     * 添加收货地址
     */
    public function addAddress(){
        $lat = $this->latitude;
        $lng = $this->longitude;
        $location = getCustomConfig('location', 'location');
        $data = array(
            'location' => $location,
            'title' => '添加收货地址',
            'add' => 1,
            'lat' =>$lat,
            'lng' =>$lng
        );

        $this->view('user/fromAddress', $data, 'wx_validation,toastmessage,layer_mobile');
    }

    /**
     * 编辑收货地址
     */
    public function editAddress(){
        $id = (int)get('id');
        $lat = trim(get('latitude'));
        $lng = trim(get('longitude'));
        if (!$id){
            show_404();
        }
        $this->loadModel('ConsumerAddressModel', 'mAddress','consumer');
        $info = $this->mAddress->getInfo($id, $this->userId);
        if ( ! $info){
            show_404();
        }
        $location = getCustomConfig('location', 'location');
        $data = array(
            'info' => $info,
            'location' => $location,
            'title' => '编辑收货地址',
            'add' => 0,
            'lat' =>$lat,
            'lng' =>$lng
        );
        $this->view('user/fromAddress', $data, 'wx_validation,toastmessage,layer_mobile');
    }

    /**
     * 添加收货地址
     */
    public function saveAddress(){
        //表单验证
        $vConf = array(
            array('consignee', '收货人名称', 'required'),
            array('gender', '性别', 'required|in_list[1,2]'),
            array('mobile', '电话', 'required|valid_mobile'),
            array('province', '省份id', 'required|is_natural_no_zero'),
            array('city', '市id', 'required|is_natural_no_zero'),
            array('county', '区id', 'required|is_natural_no_zero'),
            array('address', '详细地址', 'required'),
            array('latitude', '经度', 'required'),
            array('longitude', '纬度', 'required'),
            array('street', '街道门牌号', 'required'),
        );
        $this->formDataValidation($vConf);

        $addressId= trim(post('address_id'));//地址id 【有则 编辑】

        $consignee = trim(post('consignee'));
        $gender = trim(post('gender'));
        $mobile = trim(post('mobile'));
        $province = trim(post('province'));
        $city = trim(post('city'));
        $county = trim(post('county'));
        $address = trim(post('address'));
        $latitude = trim(post('latitude'));
        $longitude = trim(post('longitude'));
        $street = trim(post('street'));

        $lat = trim(post('lat'));//来源地址
        $lng = trim(post('lng'));

        $addressIds = array();
        if (!in_array($province, $addressIds)){
            $addressIds[] = $province;
        }
        if (!in_array($city, $addressIds)){
            $addressIds[] = $city;
        }
        if (!in_array($county, $addressIds)){
            $addressIds[] = $county;
        }

        $address_str = '';
        if ($addressIds){
            $this->loadModel('AdmSettingModel','mSetting','admin');
            $tAddress = $this->mSetting->getLocationNameByIds($addressIds);
            $address_str = $tAddress[$province]['name'] . $tAddress[$city]['name'] . $tAddress[$county]['name'].$address;
        }

        if ( ! $address_str){
            $this->appReturn(0,'地址不存在');
        }
        //地址验证
//        $tVerAddress = $this->verifyAddress($address_str,$latitude,$longitude);
//        if ( ! $tVerAddress['status']){
//            $this->appReturn(0,$tVerAddress['message']);
//        }

        //数据
        $this->loadModel('ConsumerAddressModel', 'mAddress','consumer');

        $data = array(
            'consumer_id'=>$this->userId,
            'consignee'=>$consignee,
            'gender'=>$gender,
            'mobile'=>$mobile,
            'province'=>$province,
            'city'=>$city,
            'county'=>$county,
            'address'=>$address,
            'latitude'=>$latitude,
            'longitude'=>$longitude,
            'street'=>$street,
        );

        if ($addressId){
            if( ! $this->mAddress->save($data,$addressId)){
                $this->ajaxReturn(0,'保存失败');
            }
        }else{
            //如果没有地址
            $data['is_default'] = 1;
            if ( ! $this->mAddress->getInfo(0,$this->userId)){
                $data['is_default'] = 2;
            }

            $data['addtime'] = time();
            if( ! $this->mAddress->save($data)){
                $this->ajaxReturn(0,'保存失败');
            }
        }

        $this->ajaxReturn(1,'保存成功', null, getUrl("user/address?latitude={$lat}&longitude={$lng}"));
    }

    /**
     * 验证地址是否准确
     * @param $address
     * @param $latitude
     * @param $longitude
     * @return array
     */
    private function verifyAddress($address,$latitude, $longitude){
        $this->loadModel('AdmSettingModel', 'mSett', 'admin');
        $this->loadModel('DlnOrderModel', 'mDln', 'deliveryman');

        $config = $this->mSett->get('map_key', 'deliveryman');

        $url = 'http://api.map.baidu.com/geocoder/v2/?address='.$address.'&output=json&ak='.$config;
        $tA = $this->mDln->_request($url);

        if($tA == false){
            return ['status' => 0, 'message' => '地址解析错误'];
        }

        $tS = getDistance($latitude, $longitude, $tA[0], $tA[1]);

        if( ! is_numeric($tS) || $tS > 100){
            return ['status' => 0, 'message' => '当前地址与经纬度有误差'.$tS];
        }
        return ['status'=>1,'message'=>''];
    }

    /**
     * 移除收货地址
     * 地址如果使用过，或者有关联，则假删
     */
    public function rmAddress(){
        //表单验证
        $vConf = array(
            array('address_id', '地址id', 'required|is_natural_no_zero'),
        );
        $this->formDataValidation($vConf, array('address_id' => get('address_id')));

        $addressId = trim(get('address_id'));

        $this->loadModel('ConsumerAddressModel', 'mAddress','consumer');

        if ( ! $this->mAddress->getInfo($addressId, $this->userId)){
            $this->ajaxReturn(0,'已经删除了');
        }

        //删除
        if ( ! $this->mAddress->deleteAddress($addressId, $this->userId)){
            $this->ajaxReturn(0,'删除失败');
        }

        $this->ajaxReturn(1,'删除成功', '', getUrl('user/address'));
    }

    /**
     * 设置默认地址
     */
    public function setAddressDefault(){
        //表单验证
        $vConf = array(
            array('address_id', '地址id', 'required|is_natural_no_zero'),
        );
        $this->formDataValidation($vConf);

        $addressId = trim(post('address_id'));

        $this->loadModel('ConsumerAddressModel', 'mAddress','consumer');
        if ( ! $this->mAddress->getInfo($addressId, $this->userId)){
            $this->ajaxReturn(0,'没有该地址');
        }

        if ( ! $this->mAddress->save(array('is_default'=>1),0,$this->userId)){
            $this->ajaxReturn(0,'设置失败');
        }

        if ( ! $this->mAddress->save(array('is_default'=>2),$addressId)){
            $this->ajaxReturn(0,'设置失败');
        }

        $this->ajaxReturn(1,'设置成功');
    }

    /**
     * 获取默认地址
     */
    public function getAddressDefault(){
    	$this->loadModel('ConsumerAddressModel', 'mAddress', 'consumer');
    	$tA = $this->mAddress->getDefaultAddress($this->userId);
    	$this->ajaxReturn(1,'获取成功',$tA);
    }

    ////////////////////////////////////////////////////////////
    //-----------------------------------------------
    //|	余额
    //-----------------------------------------------
    /**
     * 获取余额记录
     */
    public function getBalanceLog(){
    	//表单验证
    	$vConf = array(
//     			array('time', '时间', 'required'),
    			array('page', '分页', 'required|is_natural_no_zero'),
    	);
    	$this->formDataValidation($vConf);
    	
    	$page = trim(post('page'));
    	$time = trim(post('time'));
    	$type = trim(post('type'));
    	
    	$tA['balance'] = $this->userBalance;
    	$tA['list'] = $this->mUser->appGetBuyLogList($this->userId,$type,$time,$page);
    	$this->ajaxReturn(1,'',$tA);
    }
    
    ////////////////////////////////////////////////////////////
    //-----------------------------------------------
    //|	银行卡
    //-----------------------------------------------
    /**
     * 获取银行卡列表
     */
    public function getBankList(){
    	//表单验证
    	$vConf = array(
    			array('type_id', '银行卡类型', 'required|is_natural_no_zero'),
//     			array('page', '分页', 'required|is_natural_no_zero'),
    	);
    	$this->formDataValidation($vConf);
    	
    	$typeId = trim(post('type_id'));
    	$page = trim(post('page'));
    	
    	$this->loadModel('ConsumerBankModel', 'mBank', 'consumer');
    	$tA = $this->mBank->appGetBankList($this->userId,$typeId);
    	foreach ($tA as $k=>$v){
    		$tA[$k]['account_number'] = $this->mBank->HidesNumber($v['account_number'],4,4);
    	}
    	
    	$this->ajaxReturn(1,'',$tA);
    }
    
    /**
     * 增加银行卡
     */
    public function addBankCard(){
    	//表单验证
    	$vConf = array(
    			array('bank_id', '银行卡id', 'required|is_natural_no_zero'),
    			array('account_name', '卡名称', 'required'),
    			array('account_number', '卡号', 'required'),
    			array('mobile', '联系电话', 'required|valid_mobile'),
    	);
    	$this->formDataValidation($vConf);
    	
    	$bankId = trim(post('bank_id'));
    	$account_name = trim(post('account_name'));
    	$account_number = trim(post('account_number'));
    	$mobile = trim(post('mobile'));
    	
    	//获取银行卡
    	$this->loadModel('ConsumerBankModel', 'mBank', 'consumer');
    	$tBank = $this->mBank->getAdminBank($bankId);
    	if ( ! $tBank){
    		$this->ajaxReturn(0,'银行卡类型不存在');
    	}
    	
    	$data = array(
    			'consumer_id'=>$this->userId,
    			'type'=>1,
    			'icon'=>$tBank['bank_icon'],
    			'account_name'=>$account_name,
    			'account_number'=>$account_number,
    			'open_bank'=>$tBank['bank_name'],
    			'mobile'=>$mobile,
    			'addtime'=>time(),
    	);
    	
    	$tId = $this->mBank->save($data);
    	if ( ! $tId){
    		$this->ajaxReturn(0,'添加失败');
    	}
    	
    	$this->ajaxReturn(1,'添加成功');
    }
    
    /**
     * 增加支付宝
     */
    public function addAlipay(){
    	//表单验证
    	$vConf = array(
    			array('account_name', '卡名称', 'required'),
    			array('account_number', '卡号', 'required'),
    	);
    	$this->formDataValidation($vConf);
    	
    	$account_name = trim(post('account_name'));
    	$account_number = trim(post('account_number'));
    	
    	//获取银行卡
    	$this->loadModel('ConsumerBankModel', 'mBank', 'consumer');
    	
    	$data = array(
    			'consumer_id'=>$this->userId,
    			'type'=>2,
    			'icon'=>'',
    			'account_name'=>$account_name,
    			'account_number'=>$account_number,
    			'open_bank'=>'支付宝',
    			'mobile'=>$account_number,
    			'addtime'=>time(),
    	);
    	
    	$tId = $this->mBank->save($data);
    	if ( ! $tId){
    		$this->ajaxReturn(0,'添加失败');
    	}
    	
    	$this->ajaxReturn(1,'添加成功');
    }
    
    /**
     * 移除银行卡
     */
    public function rmBankCard(){
    	//表单验证
    	$vConf = array(
    			array('card_id', 'id', 'required'),
    	);
    	$this->formDataValidation($vConf);
    	
    	$cardId = post('card_id');
    	
    	//获取银行卡
    	$this->loadModel('ConsumerBankModel', 'mBank', 'consumer');
    	
    	if ( ! $this->mBank->getInfo($cardId,$this->userId)){
    		$this->ajaxReturn(0,'银行卡不存在');
    	}
    	
    	//删除银行卡
    	$this->db->where('id',$cardId);
    	$this->db->where('consumer_id',$this->userId);
    	if ( ! $this->db->delete($this->mBank->tbBank)){
    		$this->ajaxReturn(0,'移除失败');
    	}
    	
    	$this->ajaxReturn(1,'移除成功');
    }
    
    /**
     * 移除支付宝
     */
 /*    public function rmAlipay(){
    	//表单验证
    	$vConf = array(
    			array('card_id', 'id', 'required'),
    	);
    	$this->formDataValidation($vConf);
    	
    	$cardId = post('card_id');
    	
    	//获取银行卡
    	$this->loadModel('ConsumerBankModel', 'mBank', 'consumer');
    	
    	if ( ! $this->mBank->getInfo($cardId,$this->userId)){
    		$this->ajaxReturn(0,'银行卡不存在');
    	}
    	
    	//删除银行卡
    	$this->db->where('id',$cardId);
    	$this->db->where('consumer_id',$this->userId);
    	if ( ! $this->db->delete($this->mBank->tbBank)){
    		$this->ajaxReturn(0,'移除失败');
    	}
    	
    	$this->ajaxReturn(1,'移除成功');
    } */
    
    ////////////////////////////////////////////////////////////
    //-----------------------------------------------
    //|	积分记录
    //-----------------------------------------------
    /**
     * 获取积分记录
     */
    public function getIntegralLog(){
    	//表单验证
    	$vConf = array(
    			array('page', '分页', 'required|is_natural_no_zero'),
    	);
    	$this->formDataValidation($vConf);
    	
    	$page = trim(post('page'));
    	$time = trim(post('time'));
    	$type = trim(post('type'));
    	
    	/**
    	 * 时间查询
    	 * @var string $starttime
    	 */
    	
    	$this->loadModel('ConsumerMallModel', 'mMall','consumer');
    	
    	$tA['integral'] = $this->userIntegral;
    	$tA['list'] = $this->mMall->appGetIntegralLogList($this->userId,$type,$time,$page);
    	
    	$this->ajaxReturn(1,'',$tA);
    	
    }

    ////////////////////////////////////////////////////////////
    //-----------------------------------------------
    //|	红包
    //-----------------------------------------------
    /**
     * 获取红包列表
     */
    public function bonus(){
    	$status = (int)get('status');//1未使用 2-使用 3-过期
    	$page = (int)get('page');
//    	$condition = post('condition');//条件
        $status = $status == 0 ? 1 : $status;
        $page = $page == 0 ? 1 : $page;
    	$this->loadModel('ConsumerPromotionModel', 'mPromotion','consumer');
    	$list = $this->mPromotion->appGetBonusLogList($this->userId,$status,$page);

        $data = array(
            'list' => $list,
            'not_use'=>(string)$this->mPromotion->appGetBonusLogList($this->userId, 1,0,true),
            'use'=>(string)$this->mPromotion->appGetBonusLogList($this->userId, 2,0,true),
            'out_date'=>(string)$this->mPromotion->appGetBonusLogList($this->userId, 3,0,true),
            'title' => '红包',
        );
        if ($status == 1){
            $this->view('discount/notUsedBonus', $data,'laytpl');
        }else if($status == 2){
            $this->view('discount/useBonus', $data,'laytpl');
        }else if($status == 3){
            $this->view('discount/outDateBonus', $data,'laytpl');
        }
    }

    /**
     * 红包动态获取
     */
    public function bonusAjax(){
    	$status = (int)get('status');//1未使用 2-使用 3-过期
    	$page = (int)get('page');
        $status = $status == 0 ? 1 : $status;
        $page = $page == 0 ? 1 : $page;
    	$this->loadModel('ConsumerPromotionModel', 'mPromotion','consumer');
    	$list = $this->mPromotion->appGetBonusLogList($this->userId,$status,$page);
        $this->ajaxReturn(1,'',$list);
    }

    /**
     * 获取包邮卡列表
     */
    public function postalCard(){
    	$status = (int)get('status');//1未使用 2-使用 3-过期
    	$page = (int)get('page');
        $status = $status == 0 ? 1 : $status;
        $page = $page == 0 ? 1 : $page;
    	$this->loadModel('ConsumerPostalCardModel', 'mPostalCard','consumer');
    	$list = $this->mPostalCard->appGetBonusLogList($this->userId,$status,$page);

        $data = array(
            'list' => $list,
            'not_use'=>(string)$this->mPostalCard->appGetBonusLogList($this->userId, 1,0,true),
            'use'=>(string)$this->mPostalCard->appGetBonusLogList($this->userId, 2,0,true),
            'out_date'=>(string)$this->mPostalCard->appGetBonusLogList($this->userId, 3,0,true),
            'title' => '包邮卡',
        );

        if ($status == 1){
            $this->view('discount/notUsedPostalCard', $data,'laytpl');
        }else if($status == 2){
            $this->view('discount/usePostalCard', $data,'laytpl');
        }else if($status == 3){
            $this->view('discount/outPostalCard', $data,'laytpl');
        }
    }

    /**
     * 我的包邮卡动态加载
     */
    public function postalCardAjax(){
    	$status = (int)get('status');//1未使用 2-使用 3-过期
    	$page = (int)get('page');
        $status = $status == 0 ? 1 : $status;
        $page = $page == 0 ? 1 : $page;
    	$this->loadModel('ConsumerPostalCardModel', 'mPostalCard','consumer');
    	$list = $this->mPostalCard->appGetBonusLogList($this->userId,$status,$page);
        $this->ajaxReturn(1,'',$list);
    }

    ////////////////////////////////////////////////////////////
    //-----------------------------------------------
    //|	代金劵
    //-----------------------------------------------
    /**
     * 获取代金劵列表
     */
    public function coupon(){
    	$status = (int)get('status');//1未使用 2-使用 3-过期
    	$page = (int)get('page');
        $status = $status == 0 ? 1 : $status;
        $page = $page == 0 ? 1 : $page;
//    	$condition = post('condition');//条件
//    	$merchantId = post('merchant_id');//条件
//
//    	if ($condition && ! $merchantId){
//	    	//商家id没有传，也为空
//	    	$this->ajaxReturn(0,'商家id不能为空');
//	    }


    	$this->loadModel('ConsumerPromotionModel', 'mPromotion','consumer');
    	$tA = $this->mPromotion->appGetCouponLogList($this->userId, $status, $page);

    	if ($tA){
    		$tMerchant = array();
    		$merchantIds = array();
	    	foreach ($tA as $k=>$v){
	    		if (!in_array($v['merchant_id'], $merchantIds)){
	    			$merchantIds[] = $v['merchant_id'];
	    		}
	    	}
	    	//获取商家信息
	    	if ($merchantIds){
		    	$this->loadModel('MerchantUserModel', 'mMerchant','merchant');
		    	$tMerchant = $this->mMerchant->getInfoByIds($merchantIds);
	    	}

	    	foreach ($tA as $k=>$v){
	    		$tA[$k]['s_name'] = isset($tMerchant[$v['merchant_id']]) ? $tMerchant[$v['merchant_id']]['shop_name'] : '';
	    		$tA[$k]['s_icon'] = isset($tMerchant[$v['merchant_id']]) ? $tMerchant[$v['merchant_id']]['portrait'] : '';
	    	}
    	}
        $data = array(
            'list' => $tA,
            'not_use'=>(string)$this->mPromotion->appGetCouponLogList($this->userId, 1,0,true),
            'use'=>(string)$this->mPromotion->appGetCouponLogList($this->userId, 2,0,true),
            'out_date'=>(string)$this->mPromotion->appGetCouponLogList($this->userId, 3,0,true),
            'status' => $status,
            'title' => '代金券',
        );
        if ($status == 1){
            $this->view('discount/notUsedCoupon', $data, 'laytpl');
        }else if($status == 2 || $status == 3){
            $this->view('discount/useCoupon', $data, 'laytpl');
        }
    }

    public function couponAjax(){
    	$status = (int)get('status');//1未使用 2-使用 3-过期
    	$page = (int)get('page');
        $status = $status == 0 ? 1 : $status;
        $page = $page == 0 ? 1 : $page;
    	$this->loadModel('ConsumerPromotionModel', 'mPromotion','consumer');
    	$tA = $this->mPromotion->appGetCouponLogList($this->userId, $status, $page);

    	if ($tA){
    		$tMerchant = array();
    		$merchantIds = array();
	    	foreach ($tA as $k=>$v){
	    		if (!in_array($v['merchant_id'], $merchantIds)){
	    			$merchantIds[] = $v['merchant_id'];
	    		}
	    	}
	    	//获取商家信息
	    	if ($merchantIds){
		    	$this->loadModel('MerchantUserModel', 'mMerchant','merchant');
		    	$tMerchant = $this->mMerchant->getInfoByIds($merchantIds);
	    	}

	    	foreach ($tA as $k=>$v){
	    		$tA[$k]['s_name'] = isset($tMerchant[$v['merchant_id']]) ? $tMerchant[$v['merchant_id']]['shop_name'] : '';
	    		$tA[$k]['s_icon'] = isset($tMerchant[$v['merchant_id']]) ? $tMerchant[$v['merchant_id']]['portrait'] : '';
	    	}
    	}
        $this->ajaxReturn(1,'',$tA);
    }
    
    ////////////////////////////////////////////////////////////
    //-----------------------------------------------
    //|	收藏信息
    //-----------------------------------------------

    /**
     * 获取收藏列表
     */
    public function collection(){
    	$type = (int)get('type'); //1-店铺 2便民服务
    	$page = (int)get('page');
    	$latitude = $this->latitude;
    	$longitude = $this->longitude;
        $type = $type == 0 ? 1 : $type;
        $page = $page == 0 ? 1 : $page;

    	$list = $this->mUser->appGetCollectionList($this->userId, $type,$page,$latitude,$longitude);

    	$data = array(
    	    'list' => $list,
            'title' => '收藏'
        );
    	if ($type == 1){
            $this->view('user/store', $data);
        }else if ($type == 2){
            $this->view('user/find', $data);
        }else{
//            $this->view('user/commodity', $data); // 商品信息
            show_404();
        }
    }
    
    /**
     * 添加收藏
     */
    public function saveCollection(){
    	//表单验证
    	$vConf = array(
    			array('relation_id', '收藏内容id', 'required|is_natural_no_zero'),
    			array('type', '收藏类型', 'required|is_natural_no_zero|in_list[1,2,3]'),//1 - 店铺 2 便民服务  3 便民服务关注
    	);
    	$this->formDataValidation($vConf);
    	
    	$type = trim(post('type'));
    	$relationId = trim(post('relation_id'));
        if ($type == 5){
            $name = '关注';
        }else{
            $name = '收藏';
        }
    	//获取关联的文章信息
    	switch ($type){
    		case 1:
    			//获取店铺
    			get_instance()->loadModel('MerchantUserModel', 'mMerchant', 'merchant');
    			if ( ! $tData = $this->mMerchant->getInfo($relationId)){
    				$this->ajaxReturn(0,'店铺不存在');
    			}
    			break;
            case 2:
                //获取便民服务
                get_instance()->loadModel('ConsumerOrderModel', 'mOrder', 'consumer');
                if ( ! $tData = $this->mOrder->getInfo($relationId, 0, 0, true)){
                    $this->appReturn(0,'发现不存在');
                }
                break;
            case 3:
                //获取便民服务关注
                get_instance()->loadModel('ConsumerFindCategoryModel', 'mFindCategory', 'consumer');
                if ( ! $tData = $this->mFindCategory->getInfo($relationId,true)){
                    $this->appReturn(0,'分类不存在');
                }
                break;
//    		case 2:
//    			//获取商品信息
//    			get_instance()->loadModel('ConsumerOrderModel', 'mOrder', 'consumer');
//    			if ( ! $tData = $this->mOrder->getInfo($relationId, 0, 0, true)){
//    				$this->ajaxReturn(0,'发现不存在');
//    			}
//    			break;
//            case 4:
//                //获取买家秀
//                get_instance()->loadModel('ConsumerFriendsCircleModel', 'mFriendsCircle', 'consumer');
//                if ( ! $tData = $this->mFriendsCircle->getInfo($relationId, 1, 0, true)){
//                    $this->ajaxReturn(0,'买家秀不存在');
//                }
//                break;
//            case 5:
//                //获取卖家秀
//                get_instance()->loadModel('ConsumerFriendsCircleModel', 'mFriendsCircle', 'consumer');
//                if ( ! $tData = $this->mFriendsCircle->getInfo($relationId, 2, 0, true)){
//                    $this->ajaxReturn(0,'卖家秀不存在');
//                }
//                break;
//            case 6:
//                //获取发现
//                get_instance()->loadModel('ConsumerFindCategoryModel', 'mFindCategory', 'consumer');
//                if ( ! $tData = $this->mFindCategory->getInfo($relationId,true)){
//                    $this->appReturn(0,'分类不存在');
//                }
//                break;
    		default:
    			$tData = array();
    	}
    	
    	//是否收藏
    	if ($this->mUser->hasCollection($this->userId, $relationId, $type)){
    		$this->ajaxReturn(0,'您已经'.$name);
    	}
    	
    	//收藏
    	$data = array(
            'consumer_id'=>$this->userId,
            'relation_id'=>$relationId,
            'type'=>$type,
            'addtime'=>time(),
    	);
    	
    	if ( ! $this->mUser->saveCollection($data)){
    		$this->ajaxReturn(0,$name.'失败');
    	}
    	
    	$this->ajaxReturn(1,$name.'成功');
    }
    
    /**
     * 移除收藏
     */
    public function rmCollection(){
    	//表单验证
    	$vConf = array(
    			array('relation_id', '收藏内容id', 'required|is_natural_no_zero'),
    			array('type', '收藏类型', 'required|is_natural_no_zero|in_list[1,2,3]'),//1-店铺 2 - 便民服务 3 便民服务关注
    	);
    	$this->formDataValidation($vConf);
    	
    	$relationId = trim(post('relation_id'));
    	$type = trim(post('type'));
    	
    	if ( ! $this->mUser->hasCollection($this->userId, $relationId, $type)){
    		$this->ajaxReturn(0,'已经取消了');
    	}
    	
    	if ( ! $this->mUser->removeCollection($this->userId, $relationId, $type)){
    		$this->ajaxReturn(0,'取消失败');
    	}
    	
    	$this->ajaxReturn(1,'取消成功');
    }
    
	////////////////////////////////////////////////////////////
	//-----------------------------------------------
	//|	设置
	//-----------------------------------------------

    public function setup(){
        $this->loadModel('AdmSettingModel', 'mSetting', 'admin');
        $info = $this->mSetting->get('web_service_tel,web_service_qq');
        $data = array(
            'title' => '设置',
            'web_service_tel' => $info['web_service_tel'],
            'web_service_qq' => $info['web_service_qq'],
        );
        $this->view('user/setup',$data);
    }
	
    /**
     * 获取反馈列表
     */
    public function feedbackList(){
//    	//表单验证
//    	$vConf = array(
//    			array('page', '分页', 'required|is_natural_no_zero'),
//
//    	);
//    	$this->formDataValidation($vConf);
//
//    	$page = trim(post('page'));
//
    	$this->loadModel('AdmFeedbackModel', 'mFeedback', 'admin');
    	$tA = $this->mFeedback->appGetFeedbackList($this->userId, 0, 1);
        $data = array(
            'list' => $tA['list'],
            'title' => '意见反馈'
        );
    	$this->view('user/feedbackList', $data);

    }
    
    /**
     * 提交反馈信息
     */
    public function addFeedback(){

       if($_POST){
           //表单验证
           $vConf = array(
               array('content', '反馈内容', 'required'),
           );
           $this->formDataValidation($vConf);

           $content = trim(post('content'));

           $this->loadModel('AdmFeedbackModel', 'mFeedback', 'admin');

           $data = array(
               'consumer_id'=>$this->userId,
               'merchant_id'=>0,
               'content'=>$content,
               'reply'=>'',
               'status'=>1,
               'addtime'=>time(),
           );

           if ( ! $this->mFeedback->save($data)){
               $this->ajaxReturn(0,'反馈失败');
           }

           $this->ajaxReturn(1,'反馈成功', null, getUrl('user/feedbackList'));
       }

        $this->view('user/addFeedBack', ['title' => '意见反馈'], 'wx_validation,toastmessage,layer_mobile');
    }

    
    ////////////////////////////////////////////////////////////
    //-----------------------------------------------
    //|	个人信息
    //-----------------------------------------------
    public function info(){
        $info = $this->mUser->getInfo($this->userId);
        $data = array(
            'info' => $info,
            'title' => '个人信息'
        );
        $this->view('user/info', $data, 'wx_validation,layer_mobile');
    }

    /**
     * 编辑个人信息
     */
    public function save(){
    	//表单验证
  /*   	$vConf = array(
    			array('nickname', '昵称', 'required'),
    			array('realname', '真实名称', 'required'),
    	);
    	$this->formDataValidation($vConf); */
    	
    	$nickname = trim(post('nickname'));
    	$realname = trim(post('realname'));
    	
    	$data = array();
    	if ($nickname){
    		$data['nickname'] = $nickname;
    	}
    	if ($realname){
    		$data['realname'] = $realname;
    	}
    	
    	if ( ! $data){
    		$this->ajaxReturn(0,'数据错误');
    	}
    	
    	if ( ! $this->mUser->save($data,$this->userId)){
    		$this->ajaxReturn(0,'保存失败');
    	}
    	
    	$this->ajaxReturn(1,'保存成功');
    }
    
    /**
     * 获取app版本（目前只针对安卓版）
     */
    public function getAppVersionInfo(){
        $this->loadModel('AdmSettingModel', 'mSet', 'admin');
        $tA = $this->mSet->get('app_consumer_android_code,app_consumer_version,app_consumer_update_description,app_consumer_android_download_url');
        $data = array(
            'code' => $tA['app_consumer_android_code'],
            'version' => $tA['app_consumer_version'],
            'description' => $tA['app_consumer_update_description'],
            'download_url' => $tA['app_consumer_android_download_url']
        );

        $this->ajaxReturn(1, '', $data);
    }

    /**
     * 进入首页更新登录时间
     */
    public function updateLastLoginTime(){
        if ( ! $this->mUser->save(array('last_login_time'=>time()),$this->userId)){
            $this->ajaxReturn(0, '更新失败');
        }
        $this->db->trans_begin();
        $this->_addIntegral(3);
        $this->_addExperienceValue(2);
        $this->db->trans_commit();
        $this->ajaxReturn(1, '更新成功');
    }

    /**
     * 分享
     */
    public function share(){
        $parent_id = (int)get('pid');

        $this->view('user/share', ['title' => '注册享好礼','pid' => $parent_id], 'wx_validation,toastmessage,layer_mobile');
    }
    /**
     * 分享
     */
    public function shares(){
        $this->loadModel('AdmSettingModel', 'mSetting', 'admin');

        $parent_id = (int)get('pid');

        //专题信息
        $this->db->select('register_img,down_img');

        $tA = $this->mSetting->getOne($this->mSetting->tbShare);
        $img = base_url($tA['register_img']);

        $this->view('user/shares', ['title' => '注册享好礼','pid' => $parent_id, 'img'=>$img], 'wx_validation,toastmessage,layer_mobile');
    }

    /**
     * 推广
     */
    public function extend(){
        $this->loadModel('AdmSettingModel', 'mSetting', 'admin');
        $this->loadModel('ConsumerPromotionModel', 'mPromotion', 'consumer');

        $this->db->select('share_img,register_img,down_img,share_step,content');

        $tA = $this->mSetting->getOne($this->mSetting->tbShare);
        $tA['share_img'] = base_url($tA['share_img']);
        $tA['register_img'] = base_url($tA['register_img']);
        $tA['down_img'] = base_url($tA['down_img']);
        $tA['share_step'] = base_url($tA['share_step']);
        //统计
        $this->db->where('parent_id', $this->userId);
        $tA['consumerCount'] = $this->mUser->count($this->mUser->tbUser);//用户数量

        $this->db->select('sum(amount) as amount')
                ->where(array('consumer_id' => $this->userId, 'type' => 7, 'status' => 2));
        $amount = $this->mUser->getOne($this->mUser->tbBuyLog);//佣金
        $tA['amount'] = $amount['amount']?$amount['amount']:0;
        $this->db->where(array('consumer_id' => $this->userId, 'type' => 1));
        $tA['bonusCount'] = $this->mPromotion->count($this->mPromotion->tbBonusLog);//红包数量
        //分享记录
        $this->db->select('p.id, p.nickname, count(b.id) as bonusCount, count(u.id) as consumerCount')
                ->join($this->mUser->tbUser. ' p', 'p.id = u.parent_id')
                ->join($this->mPromotion->tbBonusLog. ' b', 'b.consumer_id = p.id and b.type = 1', 'left')
                ->where(array('p.status >' => 0, 'u.parent_id >' => 0))
                ->group_by('p.id')
                ->order_by('consumerCount', 'RANDOM');
        $tA['list'] = $this->mUser->getAll($this->mUser->tbUser .' u');
        //分享参数
        $sharp = $this->mSetting->get('sharp_title,sharp_icon,sharp_url,sharp_desc');
        $sharp['sharp_icon'] = getImage($sharp['sharp_icon'],'og');
        $sharp['sharp_url'] = getUrl('user/shares?pid='.$this->userId);
        $sharp['code'] = 'http://qr.liantu.com/api.php?el=l&m=10&w=200&text='.$sharp['sharp_url'];
        $share = json_encode($sharp, JSON_UNESCAPED_UNICODE);
        $reData = [
            'title' => '分享得红包',
            'share' => $share,
            'sign'=>wechat()->getSignPackage(),
            'pid' => $this->userId,
            'code' => $sharp['code'],
            'info' => $tA
        ];
        $this->view('user/extend', $reData, 'wx_validation,toastmessage,layer_mobile');
    }
}